package main.controller;

import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.model.Filters;
import main.GlobalConfig;
import main.RequestHelper;
import main.TimeHelper;
import main.UriHelper;
import main.database.AccountHelper;
import main.database.DatabaseMan;
import main.database.NotifyHelper;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import javax.servlet.http.HttpServletRequest;

@Controller
public class RenderBookCommentPageController {
    @GetMapping (value = "renderbookcomment/{id}")
    public String renderBookComment(HttpServletRequest request, ModelMap modelMap, @PathVariable(value="id") String id) {
        String uuid = RequestHelper.getUserUUIDFromRequest(request);
        boolean exist = AccountHelper.isExistFromUUID(uuid);
        boolean isAdmin = AccountHelper.isAdminFromUUID(uuid);

        String baseUrl = UriHelper.getServerBaseUri(request);
        modelMap.put("serverUri", baseUrl);

        MongoCollection<Document> collection = DatabaseMan.Instance().GetCollection(GlobalConfig.collectionNameOfBookComment);
        FindIterable<Document> findIterable = collection.find(Filters.eq("_id", new ObjectId(id)));
        MongoCursor<Document> cursor = findIterable.iterator();

        Document doc = cursor.next();
        String title = doc.get("title").toString();
        String content = doc.get("content").toString();

        modelMap.put("year2year", TimeHelper.getFormattedYear2Year());
        modelMap.put("isLogin", exist);
        modelMap.put("isAdmin", isAdmin);

        long unread = NotifyHelper.countUnreadNotify(uuid);
        modelMap.put("title", title);
        modelMap.put("content", content);
        modelMap.put("unread", unread);
        modelMap.put("siteName", GlobalConfig.siteName);
        return "renderBookCommentPage";
    }
}
